package com.bi.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bi.dto.TaoBaoIpReturnDTO;
import com.bi.dto.WsIpReturnDTO;
import com.bi.entity.RequestLog;
import com.bi.repository.RequestRepository;
import com.bi.service.RequestService;
import com.bi.utils.IPUtil;
import com.bi.utils.RequestHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;

/**
 * description:
 * author: w
 * date: Created in 2019/11/22 15:25
 * version: 1.0
 */
@Slf4j
@Service
public class RequestServiceImpl implements RequestService {
    @Resource
    private RequestRepository requestRepository;
    @Resource
    private RestTemplate restTemplate;

    @Override
    @Transactional
    public void joinIp() {
        HttpServletRequest request = RequestHolder.getHttpServletResponse();

        String ip = IPUtil.getIP(request);

        RequestLog logs = new RequestLog();
        logs.setRequestIp(ip);
        log.info(new Date()+"");
        requestRepository.save(logs);
    }

    @Override
    public void updateJob() {
        List<RequestLog> list=requestRepository.findByAddressIsNull();
        list.forEach(x->{
            save(x.getRequestIp(),x);
        });
    }

    @Async
    @Transactional
    public void save(String ip,RequestLog log){
        // result var lo="广东省", lc="东莞市"; var localAddress={city:"东莞市", province:"广东省"}
        String result = restTemplate.getForObject("http://ip.ws.126.net/ipquery?ip={ip}", String.class,ip);
        WsIpReturnDTO dto = null;
        if(result!=null){
            String jsonStr =result.split("localAddress=")[1];
            dto = JSONObject.parseObject(jsonStr,WsIpReturnDTO.class);
        }
        if(dto!=null){
            log.setAddress(dto.getProvince()+"|"+dto.getCity());
            requestRepository.save(log);
        }
    }
}
